package com.hcy.asyncfiledownload.datamodule.service.utils;

import com.hcy.asyncfiledownload.datamodule.annotion.MyExportProvider;
import com.hcy.asyncfiledownload.datamodule.annotion.ProviderType;
import com.hcy.asyncfiledownload.datamodule.service.provider.CenterHandler;
import com.hcy.asyncfiledownload.datamodule.service.provider.ExportHandler;
import lombok.extern.log4j.Log4j2;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Author huchenying
 * @Date 2022/9/6 16:07
 * @Description 启动时扫描provider
 */
@Component
@Log4j2
public class ProviderAssist implements ApplicationRunner, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void run(ApplicationArguments args) {
        Map<String, Object> controllers = applicationContext.getBeansWithAnnotation(MyExportProvider.class);
        for (Map.Entry<String, Object> entry : controllers.entrySet()) {
            Object value = entry.getValue();
            if (value instanceof ExportHandler) {
                ExportHandler handler = (ExportHandler) value;
                // 依次获取到 使用了该注解的对象
                Class<?> clazz = AopUtils.getTargetClass(value);
                // 获取当前对象 声明的注解 获取到注解后 还可以获取注解中的属性
                MyExportProvider myExportProvider = clazz.getDeclaredAnnotation(MyExportProvider.class);
                ProviderType type = myExportProvider.value();
                CenterHandler.setProvider(type, handler);
                log.info("scan provider -> {}", type.getComment());
            }
        }
    }
}
